package gphoto.servlet;

import gphoto.util.Systeme;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ImageMappingServlet extends HttpServlet {

	private final static Logger logger = Logger
			.getLogger(ImageMappingServlet.class);

	// private File dataDirectory;

	public void init() throws ServletException {
		// String dataDirectory_str =
		// getServletConfig().getInitParameter("imgDirectory");
		/*
		 * String dataDirectory_str = getInitParameter("imgDirectory"); if
		 * (dataDirectory_str == null) { throw new ServletException( "The
		 * servlet parameter 'imgDirectory' is mandatory"); } this.dataDirectory =
		 * new File(dataDirectory_str); if (!this.dataDirectory.isDirectory()) {
		 * throw new ServletException("'" + dataDirectory_str + "' doesn't exist
		 * or isn't a directory"); }
		 */
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String src = request.getPathInfo();
		if (Systeme.getOS() == Systeme.WINDOWS_OS) {
			src = src.substring(1, 2) + ":" + src.substring(2);
		}
		logger.debug("Img path : " + src);

		ServletContext context = getServletConfig().getServletContext();
		String MIMEType = context.getMimeType(src);
		if (MIMEType != null) {
			response.setContentType(MIMEType);
		}

		File srcFile = new File(src);
		if (!srcFile.isFile()) {
			response.sendError(404);
			return;
		}
		FileInputStream in = new FileInputStream(srcFile);

		OutputStream out = response.getOutputStream();
		int size = copy(in, out, 1024);
		in.close();
		response.setContentLength(size);
	}

	public static int copy(InputStream in, OutputStream out, int bufferSize)
			throws IOException {
		byte[] buffer = new byte[bufferSize];
		int nbRead;
		int size = 0;
		while ((nbRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, nbRead);
			size += nbRead;
		}
		return size;
	}
}